<template>
  <view class="XPicture">
    <image
      v-if="state.imageError"
      class="picture default"
      mode="aspectFill"
      :draggable="false"
      :src="defaultImgName"
    />
    <image
      v-else
      class="picture"
      mode="aspectFill"
      :src="imgUrl"
      :draggable="false"
      @load="state.imageError = false"
      @error="state.imageError = true"
    />
    <view
      class="cover"
      v-if="props.previewImg && !state.imageError"
      @click.stop="previewImage()"
    ></view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, reactive, watch, computed } from "vue";
import { fileUrl } from "@/util/util";
import avatar from "@/static/home3/avatar.png";
import iconImg from "@/static/img/default_icon_img.png";
import appointment from "@/static/img/default_appoint_img.png";
const props = defineProps({
  url: { type: String, required: true, default: "" },
  defaultImgName: { type: String, required: false },
  previewImg: { type: Boolean, required: false, default: false },
});
onMounted(() => {});
const imgUrl = computed(() => fileUrl(props.url));
const defaultImgName = computed(() => {
  let img;
  switch (props.defaultImgName) {
    case "none": {
      img = "";
      break;
    }
    case "avatar": {
      img = avatar;
      break;
    }
    case "appointment": {
      img = iconImg; // appointment;
      break;
    }
    default: {
      img = iconImg;
      break;
    }
  }
  return img;
});
const state = reactive({
  imageError: false,
});
function previewImage() {
  if (!props.previewImg) return;
  uni.previewImage({ current: imgUrl.value, urls: [imgUrl.value] });
}
watch(
  () => props.url,
  () => (state.imageError = false),
);
</script>

<style lang="scss" scoped>
.XPicture {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  > .picture {
    width: 100%;
    height: 100%;
  }
  > .cover {
    width: 100%;
    height: 100%;
    background: transparent;
    position: absolute;
    z-index: 2;
    left: 0;
    top: 0;
  }
}
</style>
